package io.jt808.proto.cmd;

import io.jt808.proto.items.EventSettingItem;
import io.norland.buffer.AutoBuffer;
import io.norland.annotations.Proto;
import io.norland.proto.IProto;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 事件设置
 */
@Proto("8301")
@Data
public class JT8301 implements IProto {
    /**
     * 设置类型,0：删除终端现有所有事件，该命令后不带后继字节；1：更新事件；2：追加事件； 3：修改事件；
     * 4：删除特定几项事件，之后事件项中无需带事件内容
     */
    private byte settingType;
    /**
     * 事件总数
     */
    private byte eventsCount;

    private List<EventSettingItem> events = new ArrayList<>();

    public byte[] writeToBytes() {
        AutoBuffer buff = new AutoBuffer();
        buff.writeByte(settingType);
        buff.writeByte(eventsCount);
        for (EventSettingItem ei : events) {
            buff.writeByte(ei.getEventId());
            buff.writeByte(ei.getEventLength());
            buff.writeGbkString(ei.getEventContent());
        }
        return buff.array();
    }

    public void readFromBuf(AutoBuffer buff) {
        settingType = buff.readByte();
        eventsCount = buff.readByte();
        while (buff.isReadable()) {
            EventSettingItem ei = new EventSettingItem();
            ei.setEventId(buff.readByte());
            ei.setEventLength(buff.readByte());
            ei.setEventContent(buff.readGbkString(ei.getEventLength()));
            events.add(ei);
        }

    }

//    public static void main(String[] args) {
//        byte[] bytes = new byte[]{
//                0x00,
//                0x01,
//                0x01,
//                0x05,
//                (byte) 0xBA, (byte) 0xBD, (byte) 0xD4, (byte) 0xBA,
//                0x38
//        };
//        JT8301 jt8301 = new JT8301();
//        jt8301.readFromBuf(new AutoBuffer(bytes));
//        System.out.println(new String(bytes).equals(new String(jt8301.writeToBytes())));
//    }
}